package com.ccl.iot;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ccl.iot.IOTDataType.IOTLong;
import com.ccl.iot.IOTDataType.IOTString;
import com.ccl.iot.device.IOTDevice;
import com.ccl.iot.device.IOTDeviceConst;
import com.ccl.iot.dialogs.ChangePasswordDialog;
import com.ccl.iot.dialogs.CustomDialog;
import com.ccl.iot.managers.DeviceManager;
import com.ccl.iot.managers.UserManager;
import com.ccl.iot.publics.AppManager;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.Res;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.publics.Window;
import com.ccl.iot.template.ActivityTitled;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class ManagerActivity extends ActivityTitled {
    private static final int KMESSAGE_UPDATE_INFO = 1;

    private UserManager iUserManager = null;
    private DeviceManager iDeviceManager = null;

    private TextView iAccount = null;
    private Button iUserInfo = null;
    private Button iChangePassword = null;
    private Button iLogout = null;

    private TextView iOwnDevices = null;
    private Button iManageOwnDevice = null;
    private Button iDeviceRomUpdate = null;
    private Button iDeviceChangePatch = null;

    private TextView iUnauthDevices = null;
    private Button iManageUnauthDevice = null;

    private TextView iAuthedDevices = null;
    private TextView iVersionName = null;
    private Button iManageAuthedDevice = null;
    private Button mBtnSyncData;

    //    private TextView iCacheSize = null;
    //    private Button iReleaseCache = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        iUserManager = UserManager.GetDefaultManager();
        iDeviceManager = DeviceManager.GetDefaultManager();
        iDeviceManager.setCheckRomUpgrade(true);
        initialize();
    }

    private void initialize() {
        this.setBackable(true);
        this.setTitle(R.string.Title_SystemManager);
        this.setContentView(R.layout.activity_manager);

        iAccount = (TextView) this.findViewById(R.id.iAccount);
        iUserInfo = (Button) this.findViewById(R.id.iUserInfo);
        iChangePassword = (Button) this.findViewById(R.id.iChangePassword);
        iLogout = (Button) this.findViewById(R.id.iLogoff);

        iOwnDevices = (TextView) this.findViewById(R.id.iOwnDevices);
        iManageOwnDevice = (Button) this.findViewById(R.id.iManageOwnDevices);
        iDeviceRomUpdate = (Button) this.findViewById(R.id.iDeviceRomUpdate);
        iDeviceChangePatch = (Button) this.findViewById(R.id.iDeviceChangePatch);

        iUnauthDevices = (TextView) this.findViewById(R.id.iUnauthDevices);
        iManageUnauthDevice = (Button) this.findViewById(R.id.iManageUnauthDevices);

        iAuthedDevices = (TextView) this.findViewById(R.id.iAuthedDevices);
        iVersionName = (TextView) this.findViewById(R.id.tv_version);
        iManageAuthedDevice = (Button) this.findViewById(R.id.iManageAuthedDevices);

        //        iCacheSize = (TextView) this.findViewById(R.id.iCacheSize);
        //        iReleaseCache = (Button) this.findViewById(R.id.iReleaseCache);

        mBtnSyncData = (Button) findViewById(R.id.btn_sync_data);

        PackageInfo packageInfo = AppManager.GetPackageInfo(getContext(), 0);
        String versionName = getResources().getString(R.string.Caption_Version) + packageInfo.versionName + "-" + packageInfo.versionCode;
        iVersionName.setText(versionName);

        handleButtonEvent();
    }

    private void loadInfo() {
        if (iUserManager != null) {
            boolean tLogon = iUserManager.isLogon();

            if (iAccount != null) {
                iAccount.setText(tLogon ? iUserManager.getLogonUserName() : "");
            }
            if (iChangePassword != null) {
                iChangePassword.setEnabled(tLogon);
            }
            if (iLogout != null) {
                iLogout.setEnabled(tLogon);
            }
        }

        if (iDeviceManager != null) {
            int tOwnerCount = 0;
            int tMultiFunctionCount = 0;
            //=================modify start===========================
            //			iDeviceManager.startScan(null, true);
            //=================modify end===========================

            if (iOwnDevices != null) {
                ArrayList<IOTDevice> ownerList = iDeviceManager.getList(true, IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_OWNER);
                if (ownerList != null && ownerList.size() > 0) {
                    for (IOTDevice dev : ownerList) {
                        if (dev.getDeviceInfo().iType == IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_MULTIFUNC_5525) {
                            tMultiFunctionCount++;
                        }
                    }
                    tOwnerCount = ownerList.size();
                }
                iOwnDevices.setText(String.valueOf(tOwnerCount));

                if (iManageOwnDevice != null) {
                    iManageOwnDevice.setEnabled(tOwnerCount > 0);
                    iDeviceRomUpdate.setEnabled(tOwnerCount > 0);
                    iDeviceChangePatch.setEnabled(tMultiFunctionCount > 0);
                }
            }

            if (iUnauthDevices != null) {
                tOwnerCount = iDeviceManager.getDeviceCount(true, IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_UNKNOWN,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_NONE,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_WAITTING,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_REJECT,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_QUIT);
                iUnauthDevices.setText(String.valueOf(tOwnerCount));

                if (iManageUnauthDevice != null) {
                    iManageUnauthDevice.setEnabled(tOwnerCount > 0);
                }
            }

            if (iAuthedDevices != null) {
                tOwnerCount = iDeviceManager.getDeviceCount(true, IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_READ,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_WRITE,
                        IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_FULL);
                iAuthedDevices.setText(String.valueOf(tOwnerCount));

                if (iManageAuthedDevice != null) {
                    iManageAuthedDevice.setEnabled(tOwnerCount > 0);
                }
            }
        }

        //        if (iCacheSize != null) {
        //			iCacheSize.setText(StringFactory.GetSizeDescription(IOTNetAPI.GetDatabaseFileSize(), 0));
        //            iCacheSize.setText(getDataSize(IOTNetAPI.GetDatabaseFileSize()));
        //        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (iUserManager != null) {
            iUserManager.addUserEventListener(iLoginListener);
        }

        updateInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (iUserManager != null) {
            iUserManager.removeUserEventListener(iLoginListener);
        }
    }

    private void handleButtonEvent() {
        if (iChangePassword != null) {
            iChangePassword.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ChangePasswordDialog tDialog = new ChangePasswordDialog(ManagerActivity.this);

                    tDialog.show();
                }
            });
        }

        if (iLogout != null) {
            iLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*new AlertDialog.Builder(ManagerActivity.this).setTitle(R.string.Title_LogoutDialog).setMessage(R.string.LogoutPrompt)
                            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (iUserManager != null && iUserManager.isLogon()) {
                                        if (iUserManager.logout()) {
                                            loadInfo();

                                            //											iUserManager.login(true);
                                            //                                            System.exit(0);

                                        } else {
                                            Messager.Show(R.string.Error_LogoutFailed);

                                            return;
                                        }
                                    }

                                    dialog.dismiss();
                                    ManagerActivity.this.finish();
                                }
                            }).setNegativeButton(R.string.Cancel, null).show();*/


                    final View view = View.inflate(getContext(), R.layout.view_logoff, null);
                    final CustomDialog dialog = new CustomDialog(getContext(), R.style.DialogTheme) {
                        @Override
                        public View getView() {
                            return view;
                        }
                    };
                    view.findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (iUserManager != null && iUserManager.isLogon()) {
                                if (iUserManager.logout()) {
                                    loadInfo();

                                    //											iUserManager.login(true);
                                    //                                            System.exit(0);

                                } else {
                                    Messager.Show(R.string.Error_LogoutFailed);

                                    return;
                                }
                            }
                            dialog.dismiss();
                            ManagerActivity.this.finish();
                        }
                    });

                    view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.cancel();
                        }
                    });

                    dialog.show();

                }
            });
        }

//






        //        if (iReleaseCache != null) {
        //            iReleaseCache.setOnClickListener(new View.OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    if (IOTNetAPI.RestoreDatabase()) {
        //TODO 释放缓存后自动重启的问题
                        /*new AlertDialog.Builder(ManagerActivity.this).setMessage(R.string.ReleaseCacheOK).setPositiveButton(R.string.OK, new DialogInterface.OnClickListener(){
                            @Override
							public void onClick(DialogInterface dialog, int which) {
								AlarmReceiver.AddAlarm(new AlarmReceiver.AlarmListener() {
									@Override
									public void onAlarm(long aAlarmID, long aTime, String aTag) {
										Window.ShowActivity(getApplicationContext(), StartupActivity.class, 0, "");
									}
								}, 1000, false, false, "Restart");
								
								MainManager.Suspend();
								
								System.exit(0);
							}
						}).show();*/
        //                        iCacheSize.setText("0.00kb");
        //                        Messager.Show(R.string.ReleaseCacheSuccess);
        //                    } else {
        //                        Messager.Show(R.string.Error_ReleaseCacheFailed);
        //                    }
        //                }
        //            });
        //        }

        if (iUserInfo != null) {
            iUserInfo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    final View view = View.inflate(getContext(), R.layout.view_userinfo_pwd, null);
                    final CustomDialog dialog = new CustomDialog(getContext(), R.style.DialogTheme) {
                        @Override
                        public View getView() {
                            return view;
                        }
                    };

                    final EditText etPwd = (EditText) view.findViewById(R.id.et_inputpwd);
                    etPwd.requestFocus();
                    Window.ShowInputDialog(getContext());

                    final Button btnOk = (Button) view.findViewById(R.id.btn_ok);
                    //                    btnOk.setEnabled(false);
                    Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);

                    /*etPwd.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            btnOk.setEnabled(!TextUtils.isEmpty(etPwd.getText().toString().trim()));
                        }
                    });*/

                    btnCancel.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            dialog.cancel();
                        }
                    });

                    btnOk.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            String pwd = etPwd.getText().toString().trim();
                            if (!TextUtils.isEmpty(pwd)) {
                                IOTString mobile = new IOTString();
                                IOTString emial = new IOTString();
                                IOTString question = new IOTString();
                                IOTString answer = new IOTString();
                                IOTLong loginLimit = new IOTLong();
                                if (IOTNetAPI.GetInstance().retriveUserInfo(pwd, mobile, emial, question, answer, loginLimit)) {
                                    Intent intent = new Intent(getContext(), UserInfoActivity.class);
                                    intent.putExtra("mobile", mobile.getValue());
                                    intent.putExtra("emial", emial.getValue());
                                    intent.putExtra("question", question.getValue());
                                    intent.putExtra("answer", answer.getValue());
                                    intent.putExtra("loginLimit", loginLimit.getValue() + "");
                                    intent.putExtra("pwd", pwd);

                                    startActivity(intent);
                                    dialog.cancel();

                                } else {
                                    Messager.Show(Res.GetString(getContext(), R.string.PwdError), 0);
                                }
                            } else {
                                Messager.Show(Res.GetString(getContext(), R.string.PwdError), 0);
                            }
                        }
                    });

                    dialog.show();
                }
            });
        }

    }

    private Handler iHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg != null && msg.what == KMESSAGE_UPDATE_INFO) {
                loadInfo();
            }
        }
    };

    private void updateInfo() {
        /*new Thread(new Runnable(){
            @Override
			public void run() {
				if (iDeviceManager != null){
					iDeviceManager.startScan(null, true);
					
					if (iHandler != null && iHandler.hasMessages(KMESSAGE_UPDATE_INFO) == false){
						iHandler.sendEmptyMessage(KMESSAGE_UPDATE_INFO);
					}
				}
			}
		}).start();*/

        //========================start modify================================
        ThreadPoolUtils.getInstance().addTask(new Runnable() {

            @Override
            public void run() {
                if (iDeviceManager != null) {
                    iDeviceManager.startScan(null, true);

                    if (iHandler != null && iHandler.hasMessages(KMESSAGE_UPDATE_INFO) == false) {
                        iHandler.sendEmptyMessage(KMESSAGE_UPDATE_INFO);
                    }
                }
            }
        });
        //========================start end================================

        if (iHandler != null && iHandler.hasMessages(KMESSAGE_UPDATE_INFO) == false) {
            iHandler.sendEmptyMessage(KMESSAGE_UPDATE_INFO);
        }
    }

    private UserManager.UserEventListener iLoginListener = new UserManager.UserEventListener() {
        @Override
        public void onLoginEvent(boolean aCanceled) {
            updateInfo();
        }

        @Override
        public void onPrepareLogout() {
        }

        @Override
        public void onLogout(boolean aOK) {
        }
    };

    public static String getDataSize(long size) {
        DecimalFormat formater = new DecimalFormat("####.00");
        if (size < 1024) {
            return "0.00KB";
        } else if (size < 1024 * 1024) {
            float kbsize = size / 1024f;
            return formater.format(kbsize) + "KB";
        } else if (size < 1024 * 1024 * 1024) {
            float mbsize = size / 1024f / 1024f;
            return formater.format(mbsize) + "MB";
        } else if (size < 1024 * 1024 * 1024 * 1024) {
            float gbsize = size / 1024f / 1024f / 1024f;
            return formater.format(gbsize) + "GB";
        } else {
            return "size: error";
        }
    }


    private float mDownY1;
    private int mDistance = UIUtils.dp2px(100);

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getPointerCount() == 4) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_POINTER_DOWN:
                    int actionIndexDown = event.getActionIndex();
                    if (actionIndexDown == 0) {
                        mDownY1 = event.getY(0);
                    }
                    break;
                case MotionEvent.ACTION_POINTER_UP:

                    break;

            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iDeviceManager.setCheckRomUpgrade(false);
    }

}
